﻿using System;
using System.Linq;
using System.Data;
using System.Web.UI.WebControls;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Components.Share;
using CDTM.Modules.ONLINE.Components;
using System.Collections.Generic;
using System.Web.UI;
using ASPNETVN.PORTAL.Components.Share.Controls;
using System.Net;
using System.IO;

namespace CDTM.Modules.ONLINE.HOME.Controls
{
    public enum NickType
    {
        Yahoo,
        Skype
    }

    public partial class ItemManager : ModulePage
    {
        private static List<ONLINE.Components.Online> _listUsers = new List<ONLINE.Components.Online>();

        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!PortalSecurity.HasManageAuthorization(this.ModuleID))
            //{
            //    PortalSecurity.AccessDenied();
            //}
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        public void LoadData()
        {
            //DataTable dt = Components.Online.SelectAll(this.ModuleID).Tables[0];
            //gvOnline.DataSource = dt;
            //gvOnline.DataBind();

            Guid moduleID = new Guid(this.Settings["ONLINE.ModuleID"].ToString());

            if (moduleID == Guid.Empty)
            {
                ContentPane.Controls.Add(new LiteralControl("Chưa cấu hình ONLINE.ModuleID"));
                return;
            }

            BuildPageLink();

            if (Request.QueryString["categoryid"] != null)
            {
                _listUsers = LoadData(moduleID, Convert.ToInt32(Request.QueryString["categoryid"])).OrderBy(x => x.SortOrder).ToList();
            }
            else
            {
                _listUsers = Components.Online.SelectCollectionAll(moduleID).OrderBy(x => x.SortOrder).ToList();
            }

            gvOnline.DataSource = _listUsers;
            gvOnline.DataBind();
        }

        private void BuildPageLink()
        {
            if (Request.QueryString["CategoryID"] != null)
            {
                int categoryID = Convert.ToInt32(Request.QueryString["CategoryID"]);
                PageLink pagelink = (PageLink)this.ParentControl.FindControl("MainPageLink");
                Category category = Category.Load(categoryID);
                if (category != null)
                {
                    Category parentCategory = Category.Load(category.ParentID);
                    if (parentCategory != null)
                    {
                        pagelink.AddLink(parentCategory.Title, ResolveClientUrl(HttpUrlBuilder.BuildModulePageUrl(this.ModuleID, 0, ModulePages.ItemManager, "categoryid={0}", parentCategory.ID)));

                        string url = ResolveClientUrl(HttpUrlBuilder.BuildModulePageUrl(this.ModuleID, 0, ModulePages.ItemManager, "categoryid={0}", category.ID));
                        pagelink.AddLink(category.Title, url);
                    }
                    else
                    {
                        pagelink.AddLink(category.Title, ResolveClientUrl(HttpUrlBuilder.BuildModulePageUrl(this.ModuleID, 0, ModulePages.ItemManager, "categoryid={0}", category.ID)));
                    }
                }
            }
        }

        private List<ONLINE.Components.Online> LoadData(Guid moduleID, int categoryID)
        {
            List<ONLINE.Components.Online> list = new List<ONLINE.Components.Online>();

            IList<Category> allCategories = new List<Category>();
            allCategories = Category.SelectCollectionAll(moduleID);
            IList<Category> topCategories = allCategories.Where(x => x.ID == categoryID).OrderBy(x => x.Title).ToList();

            foreach (Category topCategory in topCategories)
            {
                list.AddRange(ONLINE.Components.Online.SelectCollectionBy(moduleID, topCategory.ID));

                IList<Category> childCategories = allCategories.Where(x => x.ParentID == topCategory.ID).OrderBy(x => x.Title).ToList();

                foreach (Category childCategory in childCategories)
                {
                    list.AddRange(ONLINE.Components.Online.SelectCollectionBy(moduleID, childCategory.ID));
                }
            }

            return list;
        }

        protected void gvOnline_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Components.Online.DeleteOnline(Convert.ToInt32(gvOnline.DataKeys[e.RowIndex].Value));
            LoadData();
        }

        protected void gvOnline_PageIndexChanged(object sender, EventArgs e)
        {
            gvOnline.SelectedIndex = -1;
        }

        protected void gvOnline_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvOnline.PageIndex = e.NewPageIndex;
            LoadData();
        }

        public string GetDepartmentName(int categoryID)
        {
            Guid moduleID = new Guid(this.Settings["ONLINE.ModuleID"].ToString());

            List<Category> list = Category.SelectCollectionAll(moduleID).Where(x => x.ID == categoryID).ToList();

            return list.Count != 0 ? list[0].Title : "";
        }

        protected void gvOnline_Load(object sender, EventArgs e)
        {
            gvOnline.Columns[3].Visible = gvOnline.Columns[4].Visible =
            gvOnline.Columns[5].Visible = gvOnline.Columns[6].Visible = this.IsEditable;
            gvOnline.Columns[7].Visible = this.IsDeleteable;
        }

        protected void gvOnline_DataBound(object sender, EventArgs e)
        {

            HiddenField hdfID = null;
            Literal ltImage = null;
            HyperLink linkOnline = null;

            for (int i = 0; i < gvOnline.Rows.Count; i++)
            {
                hdfID = (HiddenField)gvOnline.Rows[i].FindControl("hdfID");
                ltImage = (Literal)gvOnline.Rows[i].FindControl("ltImage");
                linkOnline = (HyperLink)gvOnline.Rows[i].FindControl("linkOnline");

                Online item = _listUsers.Find(delegate(Online obj) { return obj.ID == int.Parse(hdfID.Value); });

                if (item == null) return;

                NickType type = (NickType)Enum.Parse(typeof(NickType), item.NickType, true);

                if (ValidateIsOnline(item.NickName, type) == true)
                {
                    ltImage.Text = "<div class='OnlineImageOn' style='margin-left:2px;'></div>";
                    linkOnline.NavigateUrl = "ymsgr:sendim?" + item.NickName;
                    linkOnline.ToolTip = item.HoTen;
                }
                else
                {
                    ltImage.Text = "<div class='OfflineImageOn' style='margin-left:2px;'></div>";
                    linkOnline.NavigateUrl = "";
                }
            }

        }

        private string FixName(string nickName)
        {
            string sRet = nickName;

            if (!String.IsNullOrEmpty(nickName))
            {
                //Xóa các ký tự '
                //sRet = nickName.Replace("'", "");

                //Tìm kí tự $ trong tên Sheet
                int iLastIndex = sRet.LastIndexOf("@");
                if (iLastIndex != -1)//Tìm thấy, loại bỏ đoạn từ $ về cuối string
                    sRet = sRet.Substring(0, iLastIndex);
            }
            return sRet;
        }

        private bool ValidateIsOnline(string nickname, NickType type)
        {
            HttpWebRequest objRequest = null;
            switch (type)
            {
                case NickType.Yahoo:
                    objRequest = (HttpWebRequest)WebRequest.Create("http://opi.yahoo.com/online?u=" + FixName(nickname) + "&m=s&t=8");
                    break;
            }

            HttpWebResponse objResponse = null;

            try
            {
                objResponse = (HttpWebResponse)objRequest.GetResponse();
            }
            catch (Exception ex) { }

            if (objResponse != null)
            {
                StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
                string msgReturn = objReader.ReadToEnd();
                objReader.Close();
                objResponse.Close();
                msgReturn = msgReturn.ToLower().Trim();


                if (msgReturn.EndsWith("is online"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

            return false;
        }

    }
}